<!--
 * @Description: 
 * @Author: 胡涛
 * @Date: 2023-09-11 21:21:30
 * @LastEditors: 胡涛
 * @LastEditTime: 2024-01-31 23:21:48
-->
<template>
  <div class="page-wrapper">
    <div class="toolbar">
      <div class="breadcrumb">
        <a-breadcrumb>
          <a-breadcrumb-item>组织架构</a-breadcrumb-item>
          <a-breadcrumb-item>组织人员管理</a-breadcrumb-item>
        </a-breadcrumb>
      </div>
      <a-space>
        <a-button
          type="primary"
          @click="showAddUsers"
          v-auth="'Create'"
          v-if="
            selectedCategory &&
            (selectedCategory.nodeType == 8 || selectedCategory.nodeType == 16)
          "
        >
          <template #icon>
            <PlusOutlined />
          </template>
          添加人员
        </a-button>
        <a-button type="primary" :loading="loading" @click="queryUsers">
          <template #icon>
            <SyncOutlined />
          </template>
          刷新
        </a-button>
        <!-- <a-button type="primary">
            <template #icon>
              <ExportOutlined />
            </template>
            导出
          </a-button> -->
      </a-space>
    </div>
    <div class="container container-with-side">
      <div class="side">
        <a-tree
          show-icon
          :selectable="true"
          :blockNode="true"
          :treeData="categoryItems"
          :fieldNames="{
            title: 'name',
            key: 'id',
            children: 'children',
          }"
          @select="onTreeSelect"
        >
          <template #icon="{ data }">
            <BuildOutlined class="tree-icon" v-if="data.nodeType == 4" />
            <ClusterOutlined class="tree-icon" v-else-if="data.nodeType == 8" />
            <BlockOutlined class="tree-icon" v-else-if="data.nodeType == 16" />
            <DesktopOutlined class="tree-icon" v-else />
          </template>
        </a-tree>
      </div>
      <div class="main">
        <div class="table table-tree">
          <a-table
            bordered
            sticky
            :columns="columns"
            :row-key="(record) => record.id"
            :data-source="dataSource"
            :pagination="false"
            :loading="loading"
            @change="handleTableChange"
          >
          </a-table>
        </div>
      </div>
    </div>
  </div>
  <add-users-view
    v-if="selectedCategory && popupModel.visible"
    v-model:visible="popupModel.visible"
    :organization-id="popupModel.id"
    :organization-name="selectedCategory.name"
    :current-users="currentOrgUserIds"
    @success="queryUsers"
  />

  <edit-user-view
    v-if="editModal.visible"
    v-model:visible="editModal.visible"
    :id="editModal.id"
    @success="queryUsers"
  />
</template>

<script lang="ts" setup>
import {
  PlusOutlined,
  ExportOutlined,
  SyncOutlined,
  EditOutlined,
  DeleteOutlined,
  ClusterOutlined,
  BuildOutlined,
  BlockOutlined,
  DesktopOutlined,
} from "@ant-design/icons-vue";
import { useListPage } from "@/helpers/pages";
import api from "@/api/organize/organization";
import { OrganizationDto, OrganizationTreeDto } from "@/api/organize/types";
import { SystemUserDto } from "@/api/system/types";
import { computed, h, onMounted, ref } from "vue";
import { PaginationConfig } from "ant-design-vue/es/pagination";
import { enumName, enums } from "@/plugins/enums";
import {
  Button,
  ButtonGroup,
  message,
  Popconfirm,
  Switch,
} from "ant-design-vue";
import { EmptyGuid, checkActionStyle } from "@/helpers";
import AddUsersView from "./AddUsers.vue";
import EditUserView from "./EditUser.vue";

const editModal = ref({ visible: false, id: "" });
const {
  loading,
  dataSource,
  columns,
  pagination,
  popupModel,
  searchModel,
  createQueryModel,
  onHandleCreate,
  onHandleUpdate,
} = useListPage<SystemUserDto, string>({
  searchModel: {
    GroupName: "Default",
  },
  columns: [
    { dataIndex: "userName", title: "用户名", width: 200 },
    { dataIndex: "name", title: "姓名", width: 200 },
    {
      dataIndex: "parentId",
      title: "所属机构",
      width: 240,
      customRender({ value }) {
        return getOrgName(value) || "-";
      },
    },
    { dataIndex: "postName", title: "职务", width: 120 },
    { dataIndex: "gender", title: "性别", width: 80, align: "center" },
    { dataIndex: "phoneNumber", title: "电话" },
    { dataIndex: "email", title: "邮箱" },
    {
      dataIndex: "action",
      title: "操作",
      width: 160,
      customRender: ({ record }: any) => {
        return h(ButtonGroup, [
          h(
            Button,
            {
              style: checkActionStyle("Update"),
              size: "small",
              type: "primary",
              ghost: true,
              onClick: () => {
                editModal.value = { visible: true, id: record.organizationId };
              },
            },
            {
              icon() {
                return [h(EditOutlined)];
              },
              default: () => {
                return "修改";
              },
            }
          ),

          h(
            Popconfirm,
            {
              title: "删除提示",
              description: "确定要将改用户移除当前部门吗？",
              onConfirm: () => {
                onDeleteItem(record);
              },
            },
            {
              default: () => {
                return h(
                  Button,
                  {
                    style: checkActionStyle("Delete"),
                    danger: true,
                    size: "small",
                  },
                  {
                    icon() {
                      return [h(DeleteOutlined)];
                    },
                    default: () => {
                      return "移除";
                    },
                  }
                );
              },
            }
          ),
        ]);
      },
    },
  ],
});

const currentOrgUserIds = computed(() => {
  if (selectedCategory.value) {
    return dataSource.value
      .filter((x) => x.parentId == selectedCategory.value.id)
      .map((x) => x.id);
  } else {
    return [];
  }
});

const getOrgName = (
  organizationId: string,
  items?: Array<OrganizationTreeDto>
) => {
  items = items || categoryItems.value;
  let item = items.find((x) => x.id == organizationId);
  if (item) {
    return item.name;
  }
  for (let i in items) {
    let sub = items[i];
    if (sub && sub.children?.length) {
      let name = getOrgName(organizationId, sub.children);
      if (name) {
        return name;
      }
    }
  }
  return null;
};

const categoryItems = ref<Array<OrganizationTreeDto>>([]);
const selectedCategory = ref<OrganizationDto>();
const onDeleteItem = async (item: SystemUserDto) => {
  let callback = message.loading("数据操作中，请稍后");
  await api.delete(item.organizationId);
  callback();
  await queryUsers();
};

const queryList = async () => {
  loading.value = true;
  categoryItems.value = await api.getTreeList(createQueryModel());
  loading.value = false;
};

const queryUsers = async () => {
  loading.value = true;
  if (selectedCategory.value) {
    dataSource.value = await api.getUsersForCode(
      selectedCategory.value.pathCode
    );
  } else {
    dataSource.value = [];
  }
  loading.value = false;
};

const handleTableChange = (pageConfig: PaginationConfig, filters: any) => {
  pagination.current = pageConfig.current;
  queryList();
};

const onTreeSelect = (
  selectedKeys: Array<string>,
  { selected, selectedNodes, node, event }: any
) => {
  if (selected) {
    selectedCategory.value = node.dataRef;
    queryUsers();
  } else {
    selectedCategory.value = null;
    queryUsers();
  }
};

/**
 * 显示添加部门用户页
 */
const showAddUsers = () => {
  popupModel.id = selectedCategory.value.id;
  popupModel.visible = true;
};

onMounted(() => {
  queryList();
});
</script>

<style lang="less" scoped>
.container-with-side {
  display: flex;
  overflow: hidden;

  .side {
    width: 240px;
    border-right: 1px solid #ddd;
    flex: none;

    .tree-icon {
      font-size: 16px;
      color: #0081ff;
    }
  }
  .main {
    flex: 1;
    padding-left: 10px;
    box-sizing: border-box;
    .table-tree {
      height: 100%;
    }
  }
}
</style>
